﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 将一个节点约束到某一个节点
    /// 用于动画节点不设置为子节点, 却要跟随移动和旋转情况下使用
    /// </summary>
    public class BondConstraintParent : MonoBehaviour
    {
        public Transform constraint;
        public Transform source;
        public bool isOffsetPosition = true;
        public bool isOffsetRotation = true;
        public Vector3 offset;
        public Quaternion offsetQuater;
        
        void Start()
        {
            CalOffset();
        }

        public void CalOffset()
        {
            offset = source.position - constraint.position;
            offsetQuater = source.rotation * constraint.rotation; //创建两个四元数之间的
        }

        void Update()
        {
            ConstraintPos();
        }

        public void ConstraintPos()
        {
            if (constraint == null)
                return;

            if (source == null)
                return;

            if (isOffsetPosition)
                constraint.position = source.position - offset;
            if (isOffsetRotation)
                constraint.rotation = source.rotation * offsetQuater;
            
        }
    }

    // 四元数偏移,先记录两个物体旋转的偏移, 然后实时设置他们旋转的偏移
    // offsetQuater = source.rotation * constraint.rotation; 
    // constraint.rotation = source.rotation * offsetQuater;
}